//
//  WYMUserAccountViewModel.swift
//  iOS11weibo
//
//  Created by 王应明 on 16/7/30.
//  Copyright © 2016年 DescendantsOftheSun. All rights reserved.
//

import UIKit

///负责处理WYMUserAccountView的业务逻辑
///网络请求
///字典转模型
///保存模型到沙盒中
///沙盒加载模型到内存中
class WYMUserAccountViewModel: NSObject {
    
    static let sharedUserAccountViewModel: WYMUserAccountViewModel = WYMUserAccountViewModel()
    var userAccount: WYMUserAccount?
    
    let userAccountFile = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last!.stringByAppendingString("/userAccount.plist")
    
    override init() {
        //读取沙盒中的账号
        super.init()
        userAccount = loadAccount()
    }
    
    //去服务器请求AccessToken
    func loadAccessToken(code: String, completion: (error: NSError?) -> Void) {
        let URLString = "https://api.weibo.com/oauth2/access_token"
        //参数
        let parmaeters = [
            "client_id": client_id,
            "client_secret": client_secret,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": redirect_uri
        ]
        
        WYMNetworkTool.sharedNetworkTool.POST(URLString, parameters: parmaeters, progress: nil, success: { (_, resopnseOjbect) -> Void in
            //  print("成功的回调\(resopnseOjbect)")
            
            let dict = resopnseOjbect as! [String: AnyObject]
            //字典转模型
            self.userAccount = WYMUserAccount(dict: dict)
            print("userAccount:\(self.userAccount)")
            //保存到沙盒中
            NSKeyedArchiver.archiveRootObject(self.userAccount!, toFile: self.userAccountFile)
            completion(error: nil)
        }) { (_, error) -> Void in
            //            print("失败的回调\(error)")
            completion(error: error)
        }
    }
    
    //加载沙盒中的账号
    private func loadAccount() -> WYMUserAccount? {
        let account = NSKeyedUnarchiver.unarchiveObjectWithFile(userAccountFile) as? WYMUserAccount
        //如果有账号需要判断是否过期
        if account != nil && account?.expiresDate?.compare(NSDate()) == NSComparisonResult.OrderedAscending {
            return account
        }
        return nil
    }
}
